<?php

namespace app\common\model\system;

use app\common\loader\ModelMerchant;
use app\common\model\BaseModel;
use app\common\traits\SystemMenuTrait;
use think\Exception;
use yiqiniu\extend\facade\Arrays;

/**
 * 系统菜单
 * Class SystemMenu
 * @package app\common\model\system
 */
class SystemMenuModel extends BaseModel
{
    use SystemMenuTrait;

    //
    protected $name = 'system_menu';

    protected $json = ['front'];
    // 设置字段信息
    protected $schema = [
        'id' => 'int',        // 菜单ID
        'title' => 'string',        // 菜单标题
        'pid' => 'int',        // 父ID
        'tree_path' => 'string',        // 层级路径
        'depth' => 'int',        // 层级
        'child' => 'int',        // 子菜单数
        'order_id' => 'int',        // 排序
        'api_page' => 'string',        // 菜单关联功能ID
        'icon' => 'string',        // 菜单图标
        'router_name' => 'string',        // 跌幅名称
        'router_label' => 'string',        // 路由标签
        'page_action' => 'string',        // 路由地址
        'router_file' => 'string',        // 路由文件路径
        'is_show' => 'int',        // 显视状态(0:隐藏,1:显视)
    ];


    /**
     * 根据用户登录后的路由菜单
     * @param array $menus
     * @param bool $node
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMenuAuth(array $menus, bool $node = false): array
    {
        $db = $this->db()->where('is_show', 1)
            ->order('order_id desc,id asc')->field('id,pid,order_id,front');
        if (!empty($menus)) {
            $db = $db->where(function ($query) use ($menus, $node) {
                $query->whereIn($node ? 'page_action' : 'id', $menus)->whereOr('pid', 0);
            });
        }
        $list = $db->select();
        $list = Arrays::toTree($list, 'id', 'pid');
        $result = [];
        foreach ($list as $item) {
            if (empty($item['children'])) {
                continue;
            }
            $front = $item['front'];
            $front['children'] = array_column($item['children'], 'front');
            $result[] = $front;
        }
        return $result;
    }

    /**
     * 删除菜单节点
     * @param $id
     * @throws \think\Exception
     */
    public function del($id): void
    {
        $this->startTrans();
        try {
            if ($this->removeOption()->where("pid", $id)->count() > 0) {
                api_exception(API_ERROR, "该权限还有下级权限,请先维护下级权限");
            }
            $pid = $this->removeOption()->where('id', $id)->value(null, "pid");
            if ($pid > 0) {
                $this->db()->removeOption()->where('id', $id)->dec("child")->update();
            }
            ModelMerchant::MerchantRolesActions()->where(["menu_id" => $id])->delete();
            $this->removeOption()->where(["id" => $id])->delete();
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            throw $e;
        }

    }

    /**
     * 保存数据
     * @param $data
     * @throws \think\Exception
     */
    public function addEdit($data): void
    {
        $this->TreeAddEdit($data);
    }
}
